from models.car_model import db, Brand, Car
from sqlalchemy import func, desc
import logging

logger = logging.getLogger(__name__)


class CarService:
    """汽车品牌和车型服务类"""

    def __init__(self):
        self.db = db

    def get_all_brands(self):
        """获取所有汽车品牌"""
        try:
            brands = Brand.query.all()
            return [brand.to_dict() for brand in brands]
        except Exception as e:
            logger.error(f"获取品牌列表失败: {str(e)}")
            return []

    def get_popular_brands(self, limit=10):
        """获取热门品牌（按车型数量排序）"""
        try:
            # 指定的热门品牌ID列表（去除蔚来，AITO改为鸿蒙智行）
            hot_brand_ids = [460, 465, 464, 474, 548, 284, 572, 439, 641]

            # 查询指定的热门品牌
            popular_brands = db.session.query(
                Brand.brand_id,
                Brand.brand_name,
                Brand.brand_intro,
                func.count(Car.id).label('car_count')
            ).join(Car, Brand.brand_id == Car.brand_id) \
                .filter(Brand.brand_id.in_(hot_brand_ids)) \
                .group_by(Brand.brand_id) \
                .order_by(desc('car_count')) \
                .limit(limit) \
                .all()

            result = []
            for brand in popular_brands:
                brand_dict = {
                    'brand_id': brand.brand_id,
                    'brand_name': brand.brand_name,
                    'brand_intro': brand.brand_intro,
                    'car_count': brand.car_count
                }
                result.append(brand_dict)

            return result
        except Exception as e:
            logger.error(f"获取热门品牌失败: {str(e)}")
            return []

    def get_cars_by_brand(self, brand_id, page=1, per_page=10):
        """根据品牌ID获取车型列表"""
        try:
            # 分页查询
            pagination = Car.query.filter_by(brand_id=brand_id).paginate(
                page=page, per_page=per_page, error_out=False
            )

            cars = [car.to_dict() for car in pagination.items]

            return {
                'cars': cars,
                'total': pagination.total,
                'page': page,
                'per_page': per_page,
                'pages': pagination.pages
            }
        except Exception as e:
            logger.error(f"获取品牌车型失败: {str(e)}")
            return {'cars': [], 'total': 0, 'page': page, 'per_page': per_page, 'pages': 0}

    def get_popular_cars_by_brand(self, brand_id, limit=3):
        """获取品牌下的热门车型（从2025年开始查找，逐年向前，按上市日期倒序排序）"""
        try:
            from datetime import datetime

            cars = []
            current_year = 2025  # 从2025年开始查找

            # 从2025年开始逐年向前查找，直到找到足够的数据
            while current_year >= 2000 and len(cars) < limit:
                # 查找当前年份的车型
                year_cars = Car.query.filter_by(brand_id=brand_id).filter(
                    Car.launch_date.isnot(None),
                    Car.launch_date >= datetime(current_year, 1, 1),
                    Car.launch_date < datetime(current_year + 1, 1, 1)
                ).order_by(Car.launch_date.desc()).all()

                # 添加到结果中，但不超过限制数量
                remaining = limit - len(cars)
                cars.extend(year_cars[:remaining])

                current_year -= 1  # 向前一年查找

            # 如果按年份查找还不够，补充没有日期的车型（按价格排序）
            if len(cars) < limit:
                remaining = limit - len(cars)
                # 先获取已有日期的车型ID
                existing_ids = [car.id for car in cars]
                # 获取没有日期的车型，按价格排序
                additional_cars = Car.query.filter_by(brand_id=brand_id).filter(
                    Car.launch_date.is_(None),
                    Car.model_price.isnot(None)
                )
                if existing_ids:
                    additional_cars = additional_cars.filter(Car.id.notin_(existing_ids))

                additional_cars = additional_cars.order_by(Car.model_price.desc()).limit(remaining).all()
                cars.extend(additional_cars)

            # 最终按上市日期倒序排序所有找到的车型
            cars_with_date = [car for car in cars if car.launch_date]
            cars_without_date = [car for car in cars if not car.launch_date]

            # 有日期的按日期倒序排序
            cars_with_date.sort(key=lambda x: x.launch_date, reverse=True)

            # 合并结果：先有日期的，后没有日期的
            final_cars = cars_with_date + cars_without_date

            return [car.to_dict() for car in final_cars]
        except Exception as e:
            logger.error(f"获取品牌热门车型失败: {str(e)}")
            return []
    
    def search_cars(self, keyword, page=1, per_page=10):
        """搜索车型"""
        try:
            if not keyword:
                return {'cars': [], 'total': 0, 'page': page, 'per_page': per_page, 'pages': 0}

            # 在品牌名、车型名、系列名中搜索
            search_pattern = f"%{keyword}%"
            query = Car.query.filter(
                Car.brand_name.like(search_pattern) |
                Car.model_name.like(search_pattern) |
                Car.series_name.like(search_pattern)
            )

            pagination = query.paginate(page=page, per_page=per_page, error_out=False)
            cars = [car.to_dict() for car in pagination.items]

            return {
                'cars': cars,
                'total': pagination.total,
                'page': page,
                'per_page': per_page,
                'pages': pagination.pages
            }
        except Exception as e:
            logger.error(f"搜索车型失败: {str(e)}")
            return {'cars': [], 'total': 0, 'page': page, 'per_page': per_page, 'pages': 0}

    def get_car_detail(self, car_id):
        """获取车型详情"""
        try:
            car = Car.query.filter_by(id=car_id).first()
            if car:
                return car.to_dict()
            return None
        except Exception as e:
            logger.error(f"获取车型详情失败: {str(e)}")
            return None
    
    def get_cars_with_filters(self, page=1, per_page=10, brand_id=None, price_range=None, min_price=None, max_price=None, 
                             energy_type=None, level=None, start_date=None, end_date=None, keyword=None, sort_by=None, order=None):
        """获取车型列表（支持多条件筛选）"""
        try:
            query = Car.query
            
            # 关键词搜索
            if keyword:
                search_pattern = f"%{keyword}%"
                query = query.filter(
                    Car.brand_name.like(search_pattern) |
                    Car.model_name.like(search_pattern) |
                    Car.series_name.like(search_pattern)
                )
            
            # 品牌筛选
            if brand_id:
                query = query.filter_by(brand_id=brand_id)
            
            # 价格区间筛选 - 优先使用price_range参数
            if price_range:
                # 根据price_range值设置对应的价格范围
                if price_range == 'under_5':
                    query = query.filter(Car.model_price < 5)
                elif price_range == '5_10':
                    query = query.filter(Car.model_price >= 5, Car.model_price < 10)
                elif price_range == '10_15':
                    query = query.filter(Car.model_price >= 10, Car.model_price < 15)
                elif price_range == '15_20':
                    query = query.filter(Car.model_price >= 15, Car.model_price < 20)
                elif price_range == '20_30':
                    query = query.filter(Car.model_price >= 20, Car.model_price < 30)
                elif price_range == '30_50':
                    query = query.filter(Car.model_price >= 30, Car.model_price < 50)
                elif price_range == 'above_50':
                    query = query.filter(Car.model_price >= 50)
            else:
                # 如果没有price_range，使用传统的min_price和max_price
                if min_price is not None:
                    query = query.filter(Car.model_price >= min_price)
                if max_price is not None:
                    query = query.filter(Car.model_price <= max_price)
            
            # 能源类型筛选
            if energy_type:
                query = query.filter_by(energy_type=energy_type)
            
            # 车辆级别筛选
            if level:
                query = query.filter_by(level=level)
            
            # 上市日期范围筛选
            if start_date:
                from datetime import datetime
                start_dt = datetime.strptime(start_date, '%Y-%m')
                query = query.filter(Car.launch_date >= start_dt)
            if end_date:
                from datetime import datetime
                end_dt = datetime.strptime(end_date + '-01', '%Y-%m-%d')
                # 计算下个月的第一天作为结束日期
                if end_dt.month == 12:
                    next_month = datetime(end_dt.year + 1, 1, 1)
                else:
                    next_month = datetime(end_dt.year, end_dt.month + 1, 1)
                query = query.filter(Car.launch_date < next_month)
            
            # 排序处理
            if sort_by == 'price':
                if order == 'asc':
                    query = query.order_by(Car.model_price.asc())
                elif order == 'desc':
                    query = query.order_by(Car.model_price.desc())
            elif sort_by == 'launch_date':
                if order == 'asc':
                    query = query.order_by(Car.launch_date.asc())
                elif order == 'desc':
                    query = query.order_by(Car.launch_date.desc())
            else:
                # 默认按上市日期倒序排序
                query = query.order_by(Car.launch_date.desc())
            
            # 分页查询
            pagination = query.paginate(page=page, per_page=per_page, error_out=False)
            
            cars = [car.to_dict() for car in pagination.items]
            
            return {
                'cars': cars,
                'total': pagination.total,
                'page': page,
                'per_page': per_page,
                'pages': pagination.pages
            }
        except Exception as e:
            logger.error(f"获取车型列表失败: {str(e)}")
            return {'cars': [], 'total': 0, 'page': page, 'per_page': per_page, 'pages': 0}
